package com.ykdl.member.kid.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.CouponFragmentAdapter;
import com.ykdl.member.kid.adapters.CouponFragmentAdapter.ViewHolder;
import com.ykdl.member.kid.adapters.CouponFragmentAdapter.onSelectListener;
import com.ykdl.member.kid.beans.RefreshToCouponEvent;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.beans.TicketBean;
import com.ykdl.member.kid.beans.TicketListBean;
import com.ykdl.member.kid.gears.MyGoodLifeActivity;
import com.ykdl.member.kid.gears.ShowFragmentActivity;
import com.ykdl.member.kid.marketcard.CardInfoActivity;
import com.ykdl.member.kid.marketcard.StoreCouponActivity;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.kid.xlist.XListView;
import com.ykdl.member.kid.xlist.XListView.IXListViewListener;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import de.greenrobot.event.EventBus;

/********************************************************************************
 * 
 ** 作者： jiafeiyu 创始时间：2015-4-27 描述： 门店货架的 优惠券fragment
 *********************************************************************************/
public class CouponFragment extends BaseFragment implements onSelectListener,
		IXListViewListener {

	private View convertView;
	private XListView mRefListView;
	private List<TicketBean> tickets = new ArrayList<TicketBean>();;
	private ShowFragmentActivity context;
	private CouponFragmentAdapter adapter;
	private Context mContext;
	private int cursor = 0;
	private int count = 20;
	private List<Integer> mCheckedList;
	private String store_id;
	private boolean isGoneBt = false;

	public CouponFragment(String store_id) {
		this.store_id = store_id;
	}

	@Override
	protected void onNewCreateView(View view) {
		convertView = view;
		context = (ShowFragmentActivity) getActivity();
		mContext = getActivity();
		setCenterView(R.layout.fragment_coupon);
		initView();
	}

	private void initView() {
		//convertView.findViewById(R.id.notice).setVisibility(View.VISIBLE);
		tickets = new ArrayList<TicketBean>();
		mCheckedList = new ArrayList<Integer>();
		mRefListView = (XListView) convertView.findViewById(R.id.mycoupon_list);
		adapter = new CouponFragmentAdapter(getActivity(), this);
		adapter.setCheckedList(mCheckedList);
		
		mRefListView.setPullLoadEnable(true);
		// 允许下拉
		mRefListView.setPullRefreshEnable(true);
		// 设置监听器
		mRefListView.setXListViewListener(this);
		mRefListView.gonefoot(false);
		mRefListView.hideFoot();
		mRefListView.setAdapter(adapter);
		setIsShowLoad(true);
		getData();
		
	}

	// 获取门店优惠卷列表
	public void getData() {
		// TODO 添加分页获取
		String url = KidConfig.UN_LINE_COUPON_LIST + store_id;
		Map<String, String> map = new HashMap<String, String>();
		map.put("cursor", String.valueOf(cursor));
		map.put("count", String.valueOf(count));
		HttpBaseRequest request = Wxxr.getInstance().getRequest(url, map, null);
		TaskManager.startHttpRequest(request, new getDataTag(),
				TicketListBean.class);
	}

	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			setIsShowLoad(false);
			if (t instanceof TicketListBean) {
				TicketListBean bean = (TicketListBean) t;
				if (bean.getError() == null) {
					if (bean.getCoupon_list() == null
							|| bean.getCoupon_list().size() == 0) {
						showErrorView(true, "暂无此类优惠券");
					} else {

						tickets.addAll(bean.getCoupon_list());
						if (bean.getNext_cursor() == bean.getTotal_number()) {
							mRefListView.endLoadMore();
							isGoneBt = true;
						} else {
							mRefListView.readyLoadMore();
							cursor = bean.getNext_cursor();
						}
						adapter.setData(tickets);
						adapter.notifyDataSetChanged();
						mRefListView.stopRefresh();
						mRefListView.showFoot();
					}
				}
			}

		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// Toast.makeText(mContext, "加载失败", 1).show();
			setIsShowLoad(false);
			showErrorView(true, null);
			mRefListView.stopRefresh();
			mRefListView.endLoadMore();
			return false;
		}

		@Override
		public void refreshCancel() {
			// mRefListView.setMoreButtoIsGon(false);
		}

	}
	private boolean isReceiveLoadingUnLine = false;
	@Override
	public boolean onSelectListener(ViewHolder holder, TicketBean bean,
			int position) {
		// TODO 这里进行点击选择按钮的操作
		if (isReceiveLoadingUnLine) {
			return false;
		}
		if (mCheckedList.contains(position)) {
			Toast.makeText(context, "已领取，无需再领", 0).show();
			return false;
		}
		
		if (!bean.isReceive_flag()) {

			if (bean.isMembers_only()) {
				if (bean.isMember_flag()) {
					// 立刻领取
					receiveCoupon(bean.getCoupon_id(), position);
					isReceiveLoadingUnLine = true;
				} else {
					// 加入领取
					goCardInfo(bean.getStore().getStore_id());
				}
			} else {
				// 立刻领取
				receiveCoupon(bean.getCoupon_id(), position);
				isReceiveLoadingUnLine = true;
			}
		} else {
			// 已领取
			Toast.makeText(context, "已领取，无需再领", 0).show();
		}

		return false;
	}

	// 领取门店卡
	public void receiveCoupon(String coupon_id, int position) {
		// TODO 添加分页获取
		String url = KidConfig.RECEIVE_COUPON + coupon_id;
		HttpParameters bodyParams = new HttpParameters();
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(url,
				bodyParams, null);
		TaskManager.startHttpRequest(request, new receiveCouponTag(position),
				ResetPasswordBean.class);
	}

	class receiveCouponTag implements ITag {

		private int position = -1;

		public receiveCouponTag(int position) {
			this.position = position;
		}

		@Override
		public void refreshUI(Object t, DataState ds) {
			isReceiveLoadingUnLine = false;
			if (t instanceof ResetPasswordBean) {
				ResetPasswordBean bean = (ResetPasswordBean) t;
				if (bean.getError() == null) {
					// 领取成功
					if (!mCheckedList.contains(position)) {
						mCheckedList.add(position);
					}
					adapter.notifyDataSetChanged();
					EventBus.getDefault().post(new RefreshToCouponEvent(true));
				} else {
					// 领取失败

				}
			}

		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// 领取失败
			Toast.makeText(mContext, "加载失败", 1).show();
			isReceiveLoadingUnLine = false;
			return false;
		}

		@Override
		public void refreshCancel() {

		}

	}

	// 去门店详情
	public void goCardInfo(String store_id) {
		Intent intent = new Intent(getActivity(), CardInfoActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("store_id", store_id + "");
		intent.putExtra("from","false");
		startActivity(intent);
	}

	@Override
	protected void tryAgain() {
		getData();

	}

	@Override
	public void onRefresh() {
		tickets.clear();
		cursor=0;
		isGoneBt =false;
		mCheckedList.clear();
		getData();
		EventBus.getDefault().post(new RefreshToCouponEvent(true));
	}

	@Override
	public void onLoadMore() {
		if (isGoneBt == false) {
			
			getData();
		} else {
			mRefListView.endLoadMore();
			mRefListView.stopRefresh();
		}

	}
}
